package com.xuecheng.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

/**
 * @Description: // 类说明，在创建类时要填写
 * @ClassName: GlobalExceptionHandler    // 类名，会自动填充
 * @Author: MYH          // 创建者
 * @Date: 2023/1/31 16:42   // 时间
 * @Version: 1.0     // 版本
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    //处理XueChengPlusException异常，此类异常是程序员主动抛出的，可预知的
    @ResponseBody
    @ExceptionHandler(XueChengPlusException.class)//此方法捕获XueChengPlusException异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//返回状态码500
    public RestErrorResponse doXueChengPlusException(XueChengPlusException e){

        log.error("捕获异常：{}",e.getErrMessage());
        e.printStackTrace();

        String errMessage = e.getErrMessage();
        return new RestErrorResponse(errMessage);
    }


    //捕获不可预知的异常Exception
    @ResponseBody
    @ExceptionHandler(Exception.class)//此方法捕获Exception异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//返回状态码500
    public RestErrorResponse doException(Exception e){

        log.error("捕获异常：{}",e.getMessage());
        e.printStackTrace();

        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
    }

    //捕获控制层中与前端传输时的参数异常MethodArgumentNotValidException--进行数据校验
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)//此方法捕获MethodArgumentNotValidException异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//返回状态码500
    public RestErrorResponse doMethodArgumentNotValidException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();
        //校验的错误信息
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        //搜集错误
        StringBuffer errors = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            if (fieldErrors.size() > 1){
                errors.append(fieldError.getDefaultMessage()).append(",");
            }else {
                errors.append(fieldError.getDefaultMessage());
            }
        }
        return new RestErrorResponse(errors.toString());
    }

}
